#!/bin/bash
BRANCH_NAME_PATTERN="CONV2-[[:digit:]]+"
COMMIT_PREFIX_START=""
COMMIT_PREFIX_ENDING=": "
COMMIT_PREFIX_PATTERN="$COMMIT_PREFIX_START$BRANCH_NAME_PATTERN$COMMIT_PREFIX_ENDING"
CHECK_ANY_BRANCH_MENTION=0 # check any branch mention. E.g.: "Merge BRNCH-123 into sth" might have a prefix if 0

msg=$(grep "^[^#;]" $1)
if [[ -z  $msg  ]]; then
    echo 'Commit message is empty!'
    exit 1
fi

first_line=$(head -1 $1)
if [[ $first_line =~ ${COMMIT_PREFIX_PATTERN}  ]]; then
    exit 0
fi

if [ $CHECK_ANY_BRANCH_MENTION -ne 0 ]; then
    all_lines=$(grep "^[^#;]" $1)
    if [[ $all_lines =~ ${BRANCH_NAME_PATTERN}  ]]; then
        exit 0
    fi
fi

branch_ref="$(git symbolic-ref HEAD 2>/dev/null)" ||
branch_ref=""
if [[ !  -z  $branch_ref  ]]; then
    # branch_name=$(echo $branch_ref | awk -F'/' '{print $3}') # refs/heads/BRANCH-NAME -> BRANCH-NAME
    branch_name=$(jira_branch) # refs/heads/BRANCH-NAME -> BRANCH-NAME
    if [[ $branch_name =~ $BRANCH_NAME_PATTERN ]]; then # if a branch doesn't match the pattern - do not add prefix
        sed -ie "1s/^/$COMMIT_PREFIX_START$branch_name$COMMIT_PREFIX_ENDING/" $1
    fi
fi
